package com.knowswift.common.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.knowswift.common.common.Assert;

import java.util.LinkedHashMap;


public class AliSmsUtils {
    public static final String accessKey = "";
    public static final String accessSecret = "";

    public static final String TEMP_LOGIN_VERIFY = "SMS_194405114";

    public static final String TEMP_REGISTER_VERIFY = "SMS_194405112";

    public static final String TEMP_UPDATE_PASSWORD = "SMS_219545267";

    public static boolean sendSms(String phone, String template, String param) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKey, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "白蚁防治");
        request.putQueryParameter("TemplateCode", template);
        request.putQueryParameter("TemplateParam", param);
        try {
            CommonResponse response = client.getCommonResponse(request);
            LinkedHashMap<?, ?> map = JSONUtils.parseObject(response.getData());
            String code = (String) map.get("Code");
            Assert.isEqual(code, "OK", (String) map.get("Message"));
            return true;
        } catch (ClientException e) {
            return false;
        }

    }


    public static void main(String[] args) {
        sendVerifyCode("18320306595", "123456");
    }


    public static boolean sendVerifyCode(String phoneNumber, String verifyCode) {
        String s = String.format("{\"code\":\"%s\"}", verifyCode);
        return sendSms(phoneNumber, TEMP_UPDATE_PASSWORD, s);
    }

    public static boolean sendRegisterCode(String phoneNumber, String verifyCode) {
        String s = String.format("{\"code\":\"%s\"}", verifyCode);
        return sendSms(phoneNumber, TEMP_REGISTER_VERIFY, s);
    }
}
